package cn.edu.jlu.community.app.post;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.avos.avoscloud.AVException;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.edu.jlu.community.R;
import cn.edu.jlu.community.server.AppServer;
import cn.edu.jlu.community.util.Log;
import it.neokree.materialnavigationdrawer.MaterialNavigationDrawer;

/**
 * A fragment representing a list of Items.
 */
abstract public class PostListFragment extends ListFragment
        implements AppServer.LoaderCallback, SwipeRefreshLayout.OnRefreshListener {

    @InjectView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout swipeRefreshLayout;

    @InjectView(R.id.loading)
    View loadingView;
    @InjectView(R.id.empty)
    View emptyView;

    private PostListAdapter mPostListAdapter;

    protected static final String ARG_CATEGORY = "category";
    private int mCategory;

    protected String mPostType;

    /**
     * Use this factory method to create a new instance of
     * this fragment.
     *
     * @return A new instance of fragment HomeFragment.
     */
    public static <T extends PostListFragment> T newInstance(int category, String postType, Class<T> cls) {
        try {
            T fragment = cls.newInstance();
            Bundle args = new Bundle();
            args.putInt(ARG_CATEGORY, category);
            fragment.setArguments(args);
            fragment.mPostType = postType;
            return fragment;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public PostListFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mCategory = getArguments().getInt(ARG_CATEGORY);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(getLayout(), container, false);
        ButterKnife.inject(this, view);
        return view;
    }

    protected int getLayout() {
        return 0;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        swipeRefreshLayout.setOnRefreshListener(this);

        reload();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }


    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        Map<String, Object> post = (Map<String, Object>) mPostListAdapter.getItem(position);

        Bundle data = new Bundle();
        data.putString("objId", (String) post.get("objId"));
        data.putString("title", (String) post.get("title"));
        data.putString("author", (String) post.get("author"));
        data.putString("content", (String) post.get("content"));
        DateFormat formatter = SimpleDateFormat.getDateTimeInstance();
        data.putString("time",formatter.format(post.get("time")));

        PostContentFragment fragment = PostContentFragment.newInstance(data);
        Drawable drawable = (Drawable) post.get("portrait");
        if (null != drawable) {
            fragment.setPortrait(drawable);
        }

        ((MaterialNavigationDrawer) this.getActivity()).setFragmentChild(
                fragment, "查看" + mPostType);
    }

    @Override
    public void onRefresh() {
        AppServer.loadDataByCategory(mCategory, this);
    }

    @Override
    public void onFinish(Object data) {

        swipeRefreshLayout.setRefreshing(false);

        List<Map<String, Object>> postList = (List<Map<String, Object>>) data;

        if (postList.size() > 0) {
            mPostListAdapter = new PostListAdapter(getActivity(), postList);
            setListAdapter(mPostListAdapter);
        } else {
            emptyView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    reload();
                }
            });

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    getListView().setEmptyView(emptyView);
                    loadingView.setVisibility(View.GONE);
                }
            }, 1000);
        }

    }

    private void reload() {
        AppServer.loadDataByCategory(mCategory, this);
        getListView().setEmptyView(loadingView);
        emptyView.setVisibility(View.GONE);
    }

    @Override
    public void onError(AVException e) {
    }
}
